package org.tong;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Assert;
import org.apache.shiro.util.Factory;
import org.junit.Test;

public class ShiroDemo {
    public static void main(String[] args) {
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken("zhangshan", "zs");

        try {
            // 1. 登录
            subject.login(token);
            System.out.println("登录成功");

            // 2. 角色
            Assert.isTrue(SecurityUtils.getSubject().hasRole("role1"), "没有有 role1 角色");

            // 3. 权限
            Assert.isTrue(SecurityUtils.getSubject().isPermitted("permission1"), "没有permission1权限");
        } catch (UnknownAccountException e) {
            System.err.println("账号不存在");
        } catch (IncorrectCredentialsException e) {
            System.err.println("密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void encoding() {
        String password = "smallming";
        // 1. Md5Hash
        Md5Hash md5Hash = new Md5Hash(password);
        System.out.println("Md5Hash: " + md5Hash.toHex());

        // 2. Md5Hash + salt
        Md5Hash md5Hash1 = new Md5Hash(password, "salt");
        System.out.println("Md5Hash with salt: " + md5Hash1.toHex());

        // 3. Md5Hash + salt + iterator
        Md5Hash md5Hash2 = new Md5Hash(password, "salt", 3);
        System.out.println("Md5Hash with salt with iterator: " + md5Hash.toHex());
    }
}
